package api

import (
	"context"
	"net/http"
	"time"

	"xlib/log"

	"github.com/gin-gonic/gin"
	"gopkg.in/ini.v1"

	"TCP/api/module/xgd"
	D "TCP/define"
)

var (
	cfg  RouterConfig //配置
	auth string       //校验
)

type RouterConfig struct {
	BaseRouter string `json:"base_router"`
	Xgd        string `json:"xgd"`
}

//Handler handler
type Handler struct {
	ctx    context.Context
	cancel context.CancelFunc

	cfgPath string
	addr    string
	router  *gin.Engine
	srv     *http.Server
}

//NewHandler 构造函数
func NewHandler(cfgFile, addr string) (*Handler, error) {
	h := &Handler{cfgPath: cfgFile, addr: addr, router: gin.New()}
	h.ctx, h.cancel = context.WithTimeout(context.Background(), 5*time.Second)
	err := h.init()
	if err != nil {
		log.Error(err)
	}
	log.Info("new handler")
	return h, err
}

//init 初始化
func (h *Handler) init() error {
	cfgFile, err := ini.Load(h.cfgPath)
	if err != nil {
		log.Error(err)
	}
	u := cfgFile.Section("account").Key("user").String()
	p := cfgFile.Section("account").Key("pwd").String()
	auth = D.MD5(u + p)
	cfg = RouterConfig{
		BaseRouter: cfgFile.Section("router").Key("base").String(),
		Xgd:        cfgFile.Section("router").Key("xgd").String(),
	}
	h.router.Use(loggerDebug())
	if cfgFile.Section("account").Key("needKey").String() == "true" {
		h.router.Use(authentication())
	}
	h.router.LoadHTMLGlob("web/view/*")

	h.router.StaticFS("/xgd/static", http.Dir("web/static"))

	h.router.GET(cfg.BaseRouter+cfg.Xgd, xgd.Get)
	h.router.POST(cfg.BaseRouter+cfg.Xgd, xgd.Post)
	h.router.GET(cfg.BaseRouter+cfg.Xgd+"/show", xgd.ShowLogInfo)
	h.router.GET(cfg.BaseRouter+cfg.Xgd+"/info", xgd.ShowDrvInfo)

	h.srv = &http.Server{Addr: h.addr, Handler: h.router}

	return nil
}

//Start 运行服务
func (h *Handler) Start() error {
	go func() {
		err := h.srv.ListenAndServe()
		if err != nil && err != http.ErrServerClosed {
			log.Errorf("Listen: %s\n", err)
			return
		}
	}()

	log.Infof("Listening and serving HTTP on %s", h.addr)
	return nil
}

//Stop 停止服务
func (h *Handler) Stop() error {
	defer h.cancel()

	err := h.srv.Shutdown(h.ctx)
	if err != nil {
		log.Error("Server Shutdown: ", err)
		return err
	}

	log.Info("Server exiting")
	return nil
}
